package demo.publishcomsumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/***
 * @title Consumer
 * @description： 消费者，消费消息 路由键：hello-routingKey
 * @author baiji
 * @version 1.0.0
 * @create 2023/9/1 11:39
 **/
public class Consumer {

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("guest");
        factory.setPassword("guest");
        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            // 声明一个交换器 永久的交换器
            String exchangeName = "hello-exchange";
            channel.exchangeDeclare(exchangeName, "direct", true);
            // 声明队列
            String queueName = channel.queueDeclare().getQueue();
            System.out.println("队列名称：" + queueName);
            // 路由键
            String routingKey = "hello-routingKey";
            // 根据路由 绑定 队列到交换器上
            channel.queueBind(queueName, exchangeName, routingKey);
            while (true) {
                boolean autoAck = false;
                String consumerTag = "";
                channel.basicConsume(queueName, autoAck, consumerTag, new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                        String routingKey1 = envelope.getRoutingKey();
                        String contentType = properties.getContentType();
                        System.out.println("消费的路由键：" + routingKey1);
                        System.out.println("消费的内容类型：" + contentType);
                        long deliveryTag = envelope.getDeliveryTag();
                        //确认消息
                        channel.basicAck(deliveryTag, false);
                        String bodyStr = new String(body, "UTF-8");
                        System.out.println("消费的消息体内容：" + bodyStr);
                    }
                });
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
